// broadcast.js
import { getCurrentInstance, provide, inject } from 'vue';
import emitter from 'amtf/utils/emitter'

export function useEmitter(id = '') {
  const instance = getCurrentInstance();
  const dispatch = (eventName, params) => {
    emitter.emit(id + eventName, params)
  };

  // 隔离不同的组件👇
  //   const dispatch = (componentName, eventName, params) => {
  //     let parent = instance.proxy.$parent;
  //     while (parent) {
  //       if (parent.type.name === componentName) {
  //           // 触发父组件的事件
  //           parent.$emit(eventName, ...params);
  //           return;
  //       }
  //       parent = parent.$parent;
  //   }
  //   console.error(`${componentName} was not found.`);
  // };

  const broadcast = (componentName, eventName, params) => {
    if (!instance) return;
    const children = instance?.vnode.children || []; // 获取子节点
    children.forEach(child => {
      const name = child.type.name;
      if (name === componentName) {
        child.emit(eventName, ...params);
      } else {
        // 递归遍历子组件
        const childInst = getCurrentInstance(child);
        if (childInst) {
          const { emit } = childInst;
          emit('broadcast', componentName, eventName, params);
        }
      }
    });
  };

  return {
    dispatch,
    broadcast,
  };
}
